package com.itheima.tanhua.dubbo.mongo.api.impl;

import com.itheima.tanhua.api.UserLocationApi;
import com.itheima.tanhua.dto.LocationDto;
import com.itheima.tanhua.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lff
 * @date 2022/4/1
 */
@DubboService
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongo;

    /**
     * 保存地理位置
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean updateLocation(LocationDto dto) {
        //根据用户id查询是否包含位置信息
        try {
            Query q = Query.query(Criteria.where("userId").is(dto.getUserId()));
            UserLocation location = mongo.findOne(q, UserLocation.class);
            if (location == null) {
                //不存在 创建
                UserLocation userLocation = dto.toUserLocation();
                mongo.save(userLocation);
                return true;
            } else {
                //存在 修改数据
                Update update = Update.update("location", dto.toGeoJsonPoint())
                        .set("updated", System.currentTimeMillis())
                        .set("lastUpdated", location.getUpdated());
                mongo.updateFirst(q, update, UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 查询指定范围内的用户信息
     *
     * @param distance
     * @param userId
     * @return
     */
    @Override
    public List<Long> searchNear(Double distance, Long userId) {
        //查询mongo获取当前登录用户的地址
        UserLocation location = mongo.findOne(Query.query(Criteria.where("userId")
                .is(userId)), UserLocation.class);
        if (location == null) {
            return null;
        }

        //构造原点,当前用户位置
        GeoJsonPoint point = location.getLocation();
        //构造半径
        Distance d = new Distance(distance / 1000, Metrics.KILOMETERS);
        //构造圆
        Circle circle = new Circle(point, d);
        //查询
        Query q = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> locations = mongo.find(q, UserLocation.class);
        //构造放回结果 排除掉当前登录用户id的
        ArrayList<Long> result = new ArrayList<>();
        for (UserLocation userLocation : locations) {
            if (!userLocation.getUserId().equals(userId)) {
                result.add(userLocation.getUserId());
            }
        }
        return result;
    }
}
